from django.shortcuts import render, HttpResponse, redirect
from app01 import models
from django.http import JsonResponse


# Create your views here.
def outer(func):
    def inner(*args):
        status = args[0].session.get('is_login')
        if status == True:
            return func(*args)
        return redirect('/login/')

    return inner


def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    else:
        username = request.POST.get('username')
        pwd = request.POST.get('password')
        print(username,pwd)
        res = models.User.objects.filter(username=username,password=pwd)
        if res.exists():
            request.session['is_login'] = True
            request.session['user_id'] = res.first().id
            request.session['username'] = username
            #注入菜单数据
            menu_list = res.first().menus.all().values('id','title','url')
            request.session['menu_data'] = list(menu_list)
            return redirect('/manage/')
        else:
            return redirect('/login/')


@outer
def manage(request):
    userinfo = models.User.objects.all()
    return render(request, 'manage.html', {'userinfo': userinfo})



@outer
def add(request):
    if request.method == 'GET':
        role_objs = models.Role.objects.all()
        return render(request, 'add.html', {'role_objs': role_objs})
    else:
        roles = request.POST.getlist('role')
        sex = request.POST.get('sex')
        address = request.POST.get('address')
        data = request.POST.dict()
        data.pop('role')
        data.pop('sex')
        data.pop('address')

        ret = models.Userdetail.objects.create(
            sex=sex,
            addr=address,
        )
        print(ret, ret.id)
        user_obj = models.User.objects.create(
            **data,
            userdetails_id=ret.id
        )
        user_obj.roles.add(*roles)
        return redirect('/manage/')


@outer
def change(request, num):
    if request.method == 'GET':
        user_obj = models.User.objects.filter(id=num).first()
        userdetail_obj = models.Userdetail.objects.filter(id=num).first()
        role_obj = models.Role.objects.all()
        # print(user_obj, userdetail_obj, role_obj)

        return render(request, 'change.html',
                      {'user_obj': user_obj, 'userdetail_obj': userdetail_obj, 'role_obj': role_obj})
    else:
        roles = request.POST.getlist('role')
        sex = request.POST.get('sex')
        address = request.POST.get('address')
        data = request.POST.dict()
        data.pop('role')
        data.pop('sex')
        data.pop('address')
        # print(data, '>>>>>>>>>>>>>>>>>>>>')

        ret = models.Userdetail.objects.filter(id=num).update(
            sex=sex,
            addr=address,
        )
        user_obj = models.User.objects.filter(id=num)
        user_obj.update(
            **data,
            # userdetails_id=ret.id
        )
        user_obj.first().roles.set(*roles)
        return redirect('/manage/')


@outer
def shanchu(request):
    num = request.POST.get('id')
    # print(num)
    try:
        models.User.objects.get(id=num).delete()
        data = {'status': 1, 'msg': '删除成功'}
        # print(data)
        return JsonResponse(data)
    except:
        data = {'status': 0, 'msg': '删除失败'}
        # print(data)
        return JsonResponse(data)


@outer
def role_manage(request):
    return render(request, 'role_manage.html')


@outer
def user_manage(request):
    return render(request, 'user_manage.html')


def upload(request):
    if request.method == 'GET':
        return render(request, 'upload.html')

    else:
        print(request.FILES.get('avatar'))
        file_obj = request.FILES.get('avatar')
        print(file_obj.name)
        with open(file_obj.name, 'wb') as f:
            for i in file_obj.chunks():
                f.write(i)
        return redirect('/manage/')


from django.db.models import Q
@outer
def query(request):
    if request.method == 'GET':
        return render(request,'query.html')
    else:
        username = request.POST.get('usernmae')
        sex = request.POST.get('sex')
        phone = request.POST.get('phone')
        print(username,sex,phone)
        from django.db import connection, connections
        cursor = connection.cursor()  # cursor = connections['default'].cursor()
        cursor.execute('''select * from app01_user where ''')
        ret = cursor.fetchone()

